/**************************************************************************
	DataLogger.cpp

	The data logger is used as a singleton to log various types of
	information including general info, warnings, and errors.
***************************************************************************
***************************************************************************/

#include "DataLogger.h"

DataLogger * DataLogger::dlLogger;

DataLogger::DataLogger(bool bClearLog)
{
	init(bClearLog);
}

void DataLogger::init(bool bClearLog)
{
	dlLogger = NULL;
	this->pFile = NULL;
	CreateDirectory("logs/", NULL);

	if(bClearLog)
	{
		remove("logs/log.txt");
	}

	this->pFile = fopen( "logs/log.txt", "a" );
}

void DataLogger::setLevel(char chLevel)
{
	m_chLevel = chLevel;
}

int DataLogger::addEntry( char *logdata, eMessageType eMsgType )
{
	char cEntryOut[1024];
	SYSTEMTIME sysTime;
	char strMessageType[10];

	// m_chLevel represents what level of filtering 
	// we want using flagged bits.

	if(m_chLevel == -1)
	{
		return 0;
	}

	if((m_chLevel >> (eMsgType-1)&0x1) == 1 || m_chLevel == 0)
	{
		//MessageBox(NULL,"LOG","",MB_OK);
		if( this->pFile != NULL )
		{
			GetLocalTime( &sysTime );

			switch(eMsgType)
			{
				case MESSAGE_TYPE_INFO:
					strncpy(strMessageType,"INFO",sizeof("INFO"));
				break;

				case MESSAGE_TYPE_WARING:
					strncpy(strMessageType,"WARNING",sizeof("WARNING"));
				break;

				case MESSAGE_TYPE_ERROR:
					strncpy(strMessageType,"ERROR",sizeof("ERROR"));
				break;
			};

			sprintf( cEntryOut, "%02d/%02d/%d %02d:%02d   %s:	%s\n", sysTime.wMonth, sysTime.wDay, sysTime.wYear, sysTime.wHour, sysTime.wMinute, strMessageType, logdata );
			fputs( cEntryOut, this->pFile );
			fclose( this->pFile );

			return 0;
		}
	}

	return -1;
}

DataLogger::~DataLogger( )
{
	if(this->pFile)
	{
		fclose( this->pFile );
	}
}